package com.example.service;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.example.common.enums.OrderStatus;
import com.example.entity.Orders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Component
public class OrderSchedule {

    private static final Logger log = LoggerFactory.getLogger(OrderSchedule.class);

    @Resource
    private OrdersService ordersService;

    @Scheduled(fixedRate = 10 * 60 * 1000)
    public void task() {
        log.info("======================订单扫描定时任务开始执行======================");
        Orders params = new Orders();
        params.setStatus(OrderStatus.NO_ACCEPT.getValue());
        // 查询出待接单的列表
        List<Orders> ordersList = ordersService.selectAll(params);
        ordersList.forEach(orders -> {
            // 秒
            long between = DateUtil.between(DateUtil.parseDateTime(orders.getTime()), new Date(), DateUnit.SECOND);
            if (between > 600) {   // 超过5分钟未接单  自动取消
                orders.setStatus(OrderStatus.CANCEL.getValue());
                ordersService.updateById(orders);
                log.info("======================订单【" + orders.getOrderNo() + "】已取消======================");
            }
        });
        log.info("======================订单扫描定时任务执行结束======================");
    }

}
